package cn.geminis.workflow.service.service.engine;

import cn.geminis.resources.client.UserClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.CandidateManager;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author puddi
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class GeminisCandidateManager implements CandidateManager {

    private final UserClient userClient;
    private static final ThreadLocal<Map<String, List<String>>> USER_GROUP = new ThreadLocal<>();

    @Override
    public List<String> getGroupsForCandidateUser(String userId) {
        var cache = USER_GROUP.get();
        if (Objects.isNull(cache)) {
            cache = new HashMap<>();
            USER_GROUP.set(cache);
        }
        if (!cache.containsKey(userId)) {
            cache.clear();
            var groups = userClient.userRoleName(userId.split("/")[1]);
            cache.put(userId, groups);
        }
        return cache.get(userId);
    }

    public void clean() {
        USER_GROUP.remove();
    }
}
